<?php

namespace App\Store\Controllers\Wxapp\WxappGift;

use App\Common\Services\Store\Common as StoreCommon;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Store\Models\Wxapp\Gift\WxappGiftExchangelog;
use Maatwebsite\Excel\Facades\Excel;
use App\Common\Services\CommonExcelExport;
/**
 * 礼品兑换列表
 */
class WxappGiftExchangelogController extends Controller
{
    /**
     * 列表
     */
    public function getlist(Request $request){
        $list=WxappGiftExchangelog::getList($request);
        return response()->json(['code' => '000', 'msg' => '获取成功', 'data' => $list]);
    }
    /**
     * 兑换
     */
    public function doexchange(Request $request){
        $id=intval($request->id);

        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];

        if (!in_array($accountinfo['type'], [1, 2])) { //权限控制
            return response()->json(['code' => '001', 'msg' => '无权限，请使用门店端进行审核']);
        }
        $store_id = intval($accountinfo['store_ids']);

        $info=WxappGiftExchangelog::where(['cp_id'=>$cp_id,'id'=>$id,'store_id'=>$store_id])->first();
        if(!$info){
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }
        if($info->exchange_status!=1){
            return response()->json(['code' => '001', 'msg' => '已兑换不可重复操作']);
        }
        WxappGiftExchangelog::where(['cp_id'=>$cp_id,'id'=>$id,'store_id'=>$store_id])->update(['exchange_status'=>2,'exchange_at'=>time()]);
        return response()->json(['code' => '000', 'msg' => '兑换操作成功']);
    }

    /**
     * 导出
     */
    public function doexport(Request $request)
    {
        $list = WxappGiftExchangelog::getList($request)['list'];
        $exceldata = [];
        $row = [
            ['table_header'=>'礼品兑换信息'],
            [
                'store_name' => '所属门店',
                'gift_name' => '礼品名称',
                'count'=>"数量",
                'real_name' => '会员名称',
                'mobile' => '手机电话',
                'create_at' => '创建时间',
                'exchange_status'=>'状态',
            ]
        ];
        foreach ($list as $val) {
            $exceldata[] = [
                'store_name' => $val['store_info']?$val['store_info']['store_name']:'--',
                'gift_name'=> $val['gift_name'],
                'count' => $val['count'],
                'real_name' => $val['mem_info']['real_name'],
                'mobile' => $val['mem_info']['mobile'],
                'create_at' => date('Y-m-d H:i:s', $val['create_at']),
                'exchange_status'=>$val['exchange_status']==1?'未兑换':'已兑换'
            ];
        }

        $filename = '礼品兑换信息导出_' . time() . '.xlsx';
        return Excel::download(new CommonExcelExport($row, $exceldata), $filename);
    }
}
